package com.sdkx.wear_os.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import com.sdkx.wear_os.app.MyApplication
import com.sdkx.wear_os.utils.StringUtils.bytesToHexStr
import java.security.MessageDigest
import java.util.*

/**
 * 获得设备硬件标识
 *
 * @param context 上下文
 * @return 设备硬件标识
 */
fun getDeviceId(context: Context): String {

    val sbDeviceId = StringBuilder()

    //获得AndroidId(无需权限)
    val androidid = getAndroidId(context)
    //获得设备序列号(无需权限)
    val serial = getSERIAL()
    //获得硬件uuid(根据硬件相关属性，生成uuid)(无需权限)
    val uuid = getDeviceUUID().replace("-", "")

    //追加androidid
    if (androidid != null && androidid.isNotEmpty()) {
        sbDeviceId.append(androidid)
        sbDeviceId.append("|")
    }
    //追加serial
    if (serial.isNotEmpty()) {
        sbDeviceId.append(serial)
        sbDeviceId.append("|")
    }
    //追加硬件uuid
    if (uuid.isNotEmpty()) {
        sbDeviceId.append(uuid)
    }

    //生成SHA1，统一DeviceId长度
    if (sbDeviceId.isNotEmpty()) {
        try {
            val hash = getHashByString(sbDeviceId.toString())
            val sha1 = bytesToHexStr(hash)
            if (sha1.isNotEmpty()) {
                //返回最终的DeviceId
                return sha1
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }

    //如果以上硬件标识数据均无法获得，
    //则DeviceId默认使用系统随机数，这样保证DeviceId不为空
    return UUID.randomUUID().toString().replace("-", "")
}

/**
 * 获得设备的AndroidId
 *
 * @param context 上下文
 * @return 设备的AndroidId
 */
@SuppressLint("HardwareIds")
fun getAndroidId(context: Context): String? {
    try {
        return Settings.Secure.getString(
            context.contentResolver,
            Settings.Secure.ANDROID_ID
        )
    } catch (ex: Exception) {
        ex.printStackTrace()
    }
    return ""
}

/**
 * 获得设备序列号(如：WTK7N16923005607), 个别设备无法获取
 *
 * @return 设备序列号
 */
fun getSERIAL(): String {
    var serial: String = ""
    try {
        serial = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { //9.0+
            Build.getSerial()
        } else //8.0+
            Build.SERIAL
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return serial
}

/**
 * 获得设备硬件uuid
 * 使用硬件信息，计算出一个随机数
 *
 * @return 设备硬件uuid
 */
fun getDeviceUUID(): String {
    return try {
        val dev =
            "3883756" + Build.BOARD.length % 10 + Build.BRAND.length % 10 + Build.DEVICE.length % 10 + Build.HARDWARE.length % 10 + Build.ID.length % 10 + Build.MODEL.length % 10 + Build.PRODUCT.length % 10 + Build.SERIAL.length % 10
        UUID(
            dev.hashCode().toLong(),
            Build.SERIAL.hashCode().toLong()
        ).toString()
    } catch (ex: Exception) {
        ex.printStackTrace()
        ""
    }
}

/**
 * 获取IMEI
 */

@SuppressLint("HardwareIds")
fun getDeviceImei(): String {
    val telephonyManager = MyApplication.application.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
    if (telephonyManager != null) {
        return telephonyManager.deviceId
    }
    return ""
}

/**
 * 取SHA1
 * @param data 数据
 * @return 对应的hash值
 */
fun getHashByString(data: String): ByteArray {
    return try {
        val messageDigest: MessageDigest = MessageDigest.getInstance("SHA1")
        messageDigest.reset()
        messageDigest.update(data.toByteArray(charset("UTF-8")))
        messageDigest.digest()
    } catch (e: Exception) {
        "".toByteArray()
    }
}

/**
 * 获取手机型号
 *
 * @return  手机型号
 */
fun getSystemModel(): String {
    return Build.MODEL
}

/**
 * 获取手机版本
 *
 * @return  手机版本
 */
fun getSystemRelease(): String {
    return Build.VERSION.RELEASE
}

/**
 * 获取手机品牌
 *
 * @return  手机品牌
 */
fun getSystemBrand(): String {
    return Build.BRAND
}